#!/bin/bash
set -eo pipefail

# ================= 配置区 =================
PROJECT_ROOT="$(cd "$(dirname "$0")"; pwd)"

# 读取 JSON 配置
CONFIG_FILE="${PROJECT_ROOT}/frontend/forum/public/config.json"
# 提取端口信息
BACKEND_PORT=$(jq -r '.server.backendPort' $CONFIG_FILE)
FRONTEND_PORT=$(jq -r '.server.frontendPort' $CONFIG_FILE)

PID_DIR="./pids"

# =============== 函数定义 ================
force_kill_by_port() {
  echo "强制清理端口 $FRONTEND_PORT 和 $BACKEND_PORT 占用进程..."
  # 查找所有占用端口的进程（包含子进程）
  sudo lsof -i TCP:$FRONTEND_PORT -s TCP:LISTEN | awk 'NR>1 {print $2}' | xargs -r sudo kill -9
  sudo lsof -i TCP:$BACKEND_PORT -s TCP:LISTEN | awk 'NR>1 {print $2}' | xargs -r sudo kill -9
}

clean_service() {
  local name="$1"
  local pid_file="$PID_DIR/${name}.pid"

  if [ -f "$pid_file" ]; then
    local pid=$(cat "$pid_file")
    echo "正在停止${name} (PID: $pid)..."
    if kill -0 $pid 2>/dev/null; then
      # 终止进程组（包含子进程）
      kill -- -$(ps -o pgid= $pid | tr -d ' ') 2>/dev/null || true
      sleep 1
      if kill -0 $pid 2>/dev/null; then
        kill -9 $pid
        echo "${name}已强制终止"
      fi
    fi
    rm -f "$pid_file"
  fi
}

# ============== 主执行逻辑 ==============
clean_service "frontend"
clean_service "backend"
force_kill_by_port  # 二次清理确保无残留

echo "所有服务已停止"